package com.gupaoedu.pattern.jdbc;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * 2019/9/28
 * created by chenpp
 */
public class JdbcTemplate {

    private DataSource dataSource;

    public JdbcTemplate(DataSource dataSource){
        this.dataSource = dataSource;
    }

    public List<?> executeQuery(String sql, RowMapper<?> rowMapper, Object[] params){
        try {
            //1.获取连接
            Connection connection = this.getConnection();
            //2.创建语句集
            PreparedStatement pst = this.createPrepareStatement(connection,sql);
            //3.执行sql
            ResultSet rs = this.executeQuery(pst,params);
            //4.处理结果集
            List<?> result = this.handleResultSet(rowMapper,rs);
            //5.释放资源
            this.closeResource(rs,pst,connection);
            return result;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    private List<?> handleResultSet(RowMapper<?> rowMapper, ResultSet rs) throws Exception {
        List<Object> list = new ArrayList<Object>();
        int rowNum = 1;
        while (rs.next()){
            list.add(rowMapper.mapRow(rs,rowNum));
            rowNum++;
        }
        return list;
    }

    private void closeResource(ResultSet rs,PreparedStatement pst,Connection conn) throws SQLException {
        rs.close();
        pst.close();
        conn.close();
    }

    private ResultSet executeQuery(PreparedStatement pst, Object[] params) throws SQLException {
        for (int i=0;i<params.length;i++){
            pst.setObject(i,params[i]);
        }
        return pst.executeQuery();
    }

    private PreparedStatement createPrepareStatement(Connection connection, String sql) throws SQLException {
        PreparedStatement pst = connection.prepareStatement(sql);
        return pst;
    }

    private Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }

}
